package com.huan.study.esapi;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;

import java.util.concurrent.TimeUnit;

/**
 * @author huan.fu 2021/4/22 - 下午2:48
 */
public class AbstractEsApi {

    protected final RestHighLevelClient client;

    public AbstractEsApi() {
        final CredentialsProvider credentialsProvider =
                new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials("elastic", "123456"));

        client = new RestHighLevelClient(
                RestClient.builder(
                                new HttpHost("localhost", 9200, "http"),
                                new HttpHost("localhost", 9201, "http"),
                                new HttpHost("localhost", 9202, "http")
                        )
                        .setHttpClientConfigCallback(httpClientBuilder -> {
                            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                            // 设置KeepAlive为5分钟的时间
                            httpClientBuilder.setKeepAliveStrategy((response, context) -> TimeUnit.MINUTES.toMillis(5))
                                    .setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(1).setSoKeepAlive(true).build());
                            return httpClientBuilder;
                        })
        );
    }
}
